package com.heima.wemedia.filter;

import com.heima.wemedia.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Description:
 * @Version: V1.0
 */
@Slf4j
@Component
@Order(0)
public class AuthorizeFilter implements GlobalFilter {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 判断当前是否是登录请求，如果是登录则放行
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String url = request.getURI().getPath();
        if (url.contains("/login/in")) {
            return chain.filter(exchange);
        }
        //2. 获取请求头jwt token信息
        String jwtToken = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(jwtToken)) {
            //如果不存在，向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try {
            //3. 判断令牌信息是否正确
            Claims claims = AppJwtUtil.getClaimsBody(jwtToken);
            int verify = AppJwtUtil.verifyToken(claims);
            // -1：有效，0：有效，1：过期，2：过期
            if (verify > 0) {
                //   * 如果不存在或失效，则拦截
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //   * 解析JWT令牌信息
            Integer id = claims.get("id", Integer.class);
            log.info("header token id:{}, URL:{}", id, request.getURI().getPath());

            //4. 将令牌信息传递到各个微服务
            request.mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", String.valueOf(id));
            }).build();

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //5. 返回结果放行
        return chain.filter(exchange);
    }
}
